﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework.Forms;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.OrmLite;
using Open.WinKeyboardHook;
using NModbus;
using NModbus.Serial;
using System.IO.Ports;
using NModbus.Utility;
using System.IO;

namespace Terminal
{
    public partial class frmTerminal : MetroForm
    {

        BarcodeRecordsAccess access = new BarcodeRecordsAccess();
        private readonly IKeyboardInterceptor _interceptor;
       Image imageOK = Image.FromFile(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Image","OK.jpg"));
        Image imageNG = Image.FromFile(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Image", "NG.jpg"));
        SerialPort _port = null;
        public frmTerminal()
        {
            InitializeComponent();
            access.outputHandler += new output(t =>
            {
                this.metroTextBox2.Text += t;
            });
            this.metroTextBox1.Focus();
            _interceptor = new KeyboardInterceptor();
            _interceptor.KeyPress += (sender, args) =>
            {
                   metroTextBox1.Text += args.KeyChar;
            };
            this.metroTextBox1.TextChanged += (S, E) =>
            {
                if (metroTextBox1.Text.Length == 29)
                    DearwithMessage();
            };
            _port = new SerialPort("COM5");

        }

        private void metroTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void DearwithMessage()
        {

            string barcode = metroTextBox1.Text;
            metroTextBox1.Clear();
            if (barcode.Length != 29)
                return;
            metroTextBox2.Clear();
            metroTextBox3.Text = barcode + Environment.NewLine+ metroTextBox3.Text;
            access.Insert(barcode);
            metroTextBox2.Text += barcode+Environment.NewLine;
            int v = access.ValidChecking(barcode);          
            if (v == 0)
            {
                metroLabel2.ForeColor = Color.Green;
                metroTextBox2.Text += "PASS" + Environment.NewLine;
                DO(1);
                pictureBox1.BackgroundImage = imageOK;
                SaveLog("扫码信息", new string[] { barcode, "PASS" },new string[] {"二维码","结果" });
            }
            else if (v == -1)
            {
                metroLabel2.ForeColor = Color.Red;
                metroTextBox2.Text = "条码已经超过截至日期" + Environment.NewLine;
                pictureBox1.BackgroundImage = imageNG;
                DO(0);
                SaveLog("扫码信息", new string[] { barcode, "FAIL" }, new string[] { "二维码", "结果" });
            }
            else if (v == -2)
            {
                metroLabel2.ForeColor = Color.Red;
                metroTextBox2.Text = "条码已经持续使用超过30天" + Environment.NewLine;
                pictureBox1.BackgroundImage = imageNG;
                DO(0);
                SaveLog("扫码信息", new string[] { barcode, "FAIL" }, new string[] { "二维码", "结果" });
            }
            else if (v == -3)
            {
                metroLabel2.ForeColor = Color.Red;
                metroTextBox2.Text = "无结果" + Environment.NewLine;
                pictureBox1.BackgroundImage = imageNG;
                DO(0);
                SaveLog("扫码信息", new string[] { barcode, "FAIL" }, new string[] { "二维码", "结果" });
            }
            else if (v == -4)
            {
                metroLabel2.ForeColor = Color.Red;
                metroTextBox2.Text = "条码格式不正确" + Environment.NewLine;
                pictureBox1.BackgroundImage = imageNG;
                DO(0);
                SaveLog("扫码信息", new string[] { barcode, "FAIL" }, new string[] { "二维码", "结果" });
            }
        }

        private void metroCheckBox1_CheckedChanged(object sender, EventArgs e)
        {
     
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (Visible == true)
            {
                Visible = false;
            }
            else
            {
                Visible = true;
            }
        }

        private void DO(uint value)
        {
            if (!_port.IsOpen)
                _port.Open();
            SerialPortAdapter adapter = new SerialPortAdapter(_port);
            ModbusFactory factory = new ModbusFactory();
            var master = factory.CreateRtuMaster(adapter);
            master.WriteSingleRegister(1, 3, (ushort)value);

        }
        public void SaveLog(string Name, string[] values, string[] titles)
        {
            var path =@"E:\";
            var fullpath = Path.Combine(path, Name);
            if (!Directory.Exists(fullpath))
                Directory.CreateDirectory(fullpath);
            var fullname = Path.Combine(fullpath, Name + DateTime.Today.ToString("yyyyMMdd") + ".xls");
            bool Created = true;
            if (!File.Exists(fullname))
            {
                Created = false;
            }
            FileStream fs = new FileStream(fullname, FileMode.Append, FileAccess.Write);
            StreamWriter rw = new StreamWriter(fs, Encoding.Default);
            if (!Created)
            {
                var sb0 = new StringBuilder();
                sb0.Append("时间");
                sb0.Append("\t");
                foreach (var item in titles)
                {
                    sb0.Append(item);
                    sb0.Append("\t");
                }
                rw.WriteLine(sb0.ToString());
            }
            var sb1 = new StringBuilder();
            sb1.Append(DateTime.Now.ToString("HH:mm:ss"));
            sb1.Append("\t");
            foreach (var item in values)
            {
                sb1.Append(item);
                sb1.Append("\t");
            }
            rw.WriteLine(sb1.ToString());
            rw.Close();
            fs.Close();
        }

        private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
        {
            DO(0);
        }

        private void metroTextBox2_Click(object sender, EventArgs e)
        {

        }

        private void metroCheckBox1_CheckedChanged_1(object sender, EventArgs e)
        {
            if (metroCheckBox1.Checked)
            {
                _interceptor.StartCapturing();
                this.metroTextBox1.ReadOnly = true;
            }
            else
            {
                _interceptor.StopCapturing();
                this.metroTextBox1.ReadOnly = false;
            }
        }

        private void frmTerminal_Activated(object sender, EventArgs e)
        {
            this.metroTextBox1.Focus();
        }
    }
}
